import copy
from conf.db import get_db

db = get_db()


class TasksAide:
    cfg = [
        {'label': '任务名称', 'field': 'name', 'required': True},
        {'label': '任务分组', 'field': 'group_id', 'required': True},
        {'label': '执行资源', 'field': 'ecs_id', 'required': True},
        {'label': '执行时间', 'field': 'crontab_expression', 'required': True},
        {'label': '执行脚本', 'field': 'crontab_shell', 'required': True},
        {'label': '执行状态', 'field': 'status_fmt', 'required': False},
        {'label': '执行次数', 'field': 'run_count', 'required': False},
        {'label': '最新执行时间', 'field': 'last_time', 'required': False},
    ]

    @classmethod
    def edit_cfg(cls):
        cfg = copy.deepcopy(cls.cfg)
        cfg.append({'label': '任务说明', 'field': 'remark', 'required': False})
        for field in ['status_fmt', 'run_count', 'last_time']:
            for idx, itm in enumerate(cfg):
                if itm['field'] == field:
                    del cfg[idx]
                    break
        for i in cfg:
            i['type'] = 'text'
            if 'error_inform' == i['field']:
                i['type'] = 'radio'
                i['options'] = [{'name': '是', 'value': 1}, {'name': '否', 'value': 2}]
            if 'remark' == i['field']:
                i['type'] = 'textarea'
            if 'group_id' == i['field']:
                i['type'] = 'select'
                i['options'] = []
                groups = db.findAll('tasks_group', '1')
                for g in groups:
                    i['options'].append({'name': g['name'], 'value': g['id']})
            if 'ecs_id' == i['field']:
                i['type'] = 'select'
                i['options'] = []
                ecs = db.findAll('esc_resource', '1')
                for one in ecs:
                    i['options'].append({'name': one['name'], 'value': one['id']})
        return cfg

    @classmethod
    def log_list_cfg(cls):
        cfg = [
            {'label': '状态', 'field': 'status', 'required': True},
            # {'label': '结果', 'field': 'result', 'required': True},
            {'label': '时间', 'field': 'ct', 'required': True},
        ]
        return cfg

    @classmethod
    def tasks_log_list_fmt(cls, cfg, data):
        for one in cfg:
            for row in data:
                value = row.get(one['field'])
                if one['field'] in ['status']:
                    _map = {1: '成功', 10: '出错'}
                    row[one['field']] = _map.get(value)

    @classmethod
    def tasks_list_fmt(cls, cfg, data):
        for one in cfg:
            for row in data:
                value = row.get(one['field'])
                if one['field'] in ['group_id']:
                    row[one['field']] = db.find('tasks_group', 'id = {}'.format(value)).get('name')
                if one['field'] in ['ecs_id']:
                    row[one['field']] = db.find('esc_resource', 'id = {}'.format(value)).get('name')
                if one['field'] in ['status_fmt']:
                    _map = {1: '<font style="color:green;">执行中</font>', 2: '<font style="color:red;">已停止</font>'}
                    row[one['field']] = _map.get(row['status'])
                if one['field'] in ['run_count']:
                    row[one['field']] = db.count('tasks_log', 'tid = {}'.format(row['id']))
                if one['field'] in ['last_time']:
                    log = db.find('tasks_log', 'tid = {}'.format(row['id']), order='created_at DESC', field="strftime('%Y-%m-%d %H:%M:%S',created_at,'localtime') as ct")
                    if log:
                        row[one['field']] = log.get('ct')
